import StepHeader from "@page/cart/comps/StepHeader";
import ProductList from "./comps/ProductList";
import OriginalInfo from "./components/OriginalInfo";
import SubjectInfo from "./components/SubjectInfo";
import MoneyCard from "./components/MoneyCard";
import ProcurementMoney from "./components/ProcurementMoney";
import Relationship from "./components/Relationship";
import CommonUtils from "../common/utils/CommonUtils";
import HttpUtils from "../common/utils/HttpUtils";
import EventEmitterUtils from "../common/utils/EventEmitterUtils";
import Uts from "@module/Uts";
import Rest from "@module/Rest";
import addPng from "@assets/statement/add.png";
import ZenModal from "@root/components/ZenUI/ZenModal/ZenModal";
import YanKeSelectCard from "@root/P/components/YanKeSelectCard";
import ZenUI from "@root/components/ZenUI/ZenUI";
import "../cart/cart.css";
import "./statements.css";
import message from "@ui/RJMart/message";
import EventApi from "@module/EventApi";

import Steps, { Step } from "@ui/RJMart/steps";
import xuanzhong from "@root/imgs/xuanzhong.png";
// import Step from '@ui/RJMart/step'

class Statements extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            isShowCard: true,
            deptId: "",
            minusPrice: 0, //优惠金额
            // yankeCard: []
            serviceItem: 0, //服务项
            commodityItem: 1, //商品项
            hasLabel:false, //是否需要显示地址标签
            isFrozen:0 //当前所选课题组是否被冻结,0-未冻结，1-订单超时冻结，2-结算超时冻结
        };
        this.formData = {
            applyInfo: "",
            cardIds: [],
            tdeliveryAddress: {},
            ids: [],
            refCoupinIds: [],
            remarks: [],
            department: {},
            totalCarryFee: "",
            piIds:[]
        };
        const params = $state.params;
        this.cartIds = decodeURIComponent(params.ids);
        if (params.ids) {
            this.formData.ids = params.ids.split(",");
        }
        if (params.groupbuyingId) {
            this.isGroupbuying = true;
            this.productCount = params.productCount - 0;
            this.groupbuyingId = params.groupbuyingId;
        }

        this.orgId = Uts.getCookie("orgId");
    }

    componentDidMount() {
        this.loadingCartData();
        this.isShowCardByOrgId(); //是否显示经费卡
        EventEmitterUtils.on("getTotalCouponsInfo", data => {
            let _data = Uts.toJSON(data);
            // console.log(_data)
            this.totalCouponPrice = _data.totalCouponPrice;
            this.cuponRefIds = _data.cuponRefIds;
            this.setState({ minusPrice: this.totalCouponPrice || 0 });
            this.formData.refCoupinIds = this.cuponRefIds;
            if (!_data.isFrist) {
                this.getCarryFee(
                    this.formData.tdeliveryAddress.id,
                    this.formData.refCoupinIds
                );
            }
        });

        this.orgId == "3" &&
            EventApi.on("getCategoryDirectory", data => {
                var index = 0,
                    isGoing = true;
                this.formData.applyProductReqs &&
                    this.formData.applyProductReqs.forEach((val, i) => {
                        if (isGoing && data && data.productId == val.productId) {
                            (index = i), (isGoing = false);
                        }
                    });
                this.formData.applyProductReqs.splice(index, 1, data);
            });
    }

    componentWillUnmount() {
        EventEmitterUtils.off("getTotalCouponsInfo");
        EventApi.off("getCategoryDirectory");
    }

    loadingCartData() {
        if (this.isGroupbuying) {
            this.getGroupCartInfo();
        } else {
            this.loadShoppingCartCard();
        }
    }

    updateStateLabel = () => {
        console.log("updateLabel",this.state.hasLabel);
        this.setState({ hasLabel: true });
    };

    totalMoneyInParent(data, minusPrice) {
        if (data) {
            let totalMoney = 0;
            if ($state.params.groupbuyingId) {
                data.forEach((v, k) => {
                    totalMoney += Number(v.showPrice);
                });
            } else {
                data.forEach((v, k) => {
                    v.cart &&
                        v.cart.forEach((v1, k1) => {
                            totalMoney += v1.countPrice;
                        });
                });
            }

            totalMoney = totalMoney - minusPrice;
            this.totalAmount = Filter.float(totalMoney, 2);
        }
        return true;
    }

    //团购
    getGroupCartInfo(id) {
        let url = `/store/api/group-buying/application/shopping-list`;
        const cartIds = this.cartIds;
        const idArr = cartIds.split(",");
        let params = {
            productIds: idArr,
            // productIds:["100000913740"],
            // productQuantity:1,
            productQuantity: this.productCount,
            groupBuyingId: this.groupbuyingId
            // groupBuyingId:"d1e461dc-dcdf-41cc-b56e-d0b21ef0960f"
        };
        if (id) {
            params.addressID = id;
            params.isChangedAddress = 1;
        }
        Rest.post(url, params)
            .then(res => {
                console.log(res);
                // 中大去获取政府采购目录列表

                this.formData.totalCarryFee = this.priceFlool(
                    res.totalCarryFee
                );
                this.setState({
                    cartInfo: res.shoppingModels,
                    supplierName: res.supplierName,
                    serviceItem: res.serviceItem || 0,
                    commodityItem: res.commodityItem || 1
                });
            })
            .catch(err => {});
    }

    //
    loadShoppingCartCard() {
        const cartIds = this.cartIds;
        const idArr = cartIds.split(",");

        HttpUtils.loadShoppingCartCard(idArr)
            .then(res => {
                console.log(res);
                if (res.code == "0002") {
                    message.warn({
                        text: res.message || "",
                        duration: 3000
                    });
                }
                this.formData.totalCarryFee = this.totalCarryFee(
                    res.shoppingCart,
                    "totalCarryFee"
                );
                this.setState(
                    {
                        cartInfo: res.shoppingCart,
                        serviceItem: res.serviceItem || 0,
                        commodityItem: res.commodityItem || 1
                    },
                    () => {
                        if (["3"].indexOf(this.orgId) > -1) {
                            this.categoryDirectory();
                        }
                    }
                );
            })
            .catch(err => {
                console.log(err);
            });
    }

    //格式化金额
    priceFlool(data) {
        var num = Number(data);
        if (data || data == "0") {
            num = num
                .toFixed(3)
                .substring(0, num.toFixed(3).toString().length - 1);
            return num;
        }
        return num;
    }

    //运费总额
    totalCarryFee = (list, prop) => {
        let totalMoney = 0;
        if (list && list.length > 0) {
            list.forEach((v, k) => {
                totalMoney += v[prop];
            });
        }
        return this.priceFlool(totalMoney);
    };

    //项目组回调
    changeDep = result => {
        if (result) {
            console.log("changeDep", result);
            let data = result;
            this.setState({
                deptId: data.id
            });
        }
        this.formData.department = result;
        this.formData.cardIds = []; //切换课题组时清空之前所选择经费卡
    };

    //地址回调
    addressBc = (data, first) => {
        if (data === "add") {
            this.setState({
                isShowAddressModal: true
            });
        } else {
            let _data = data;
            _data.address = _data.deliveryAdress;
            //切换地址重新计算运费
            if (
                !first &&
                this.formData.tdeliveryAddress &&
                this.formData.tdeliveryAddress.id != _data.id
            ) {
                if ($state.params.groupbuyingId) {
                    this.getGroupCartInfo(_data.id);
                } else {
                    this.getCarryFee(_data.id, this.formData.refCoupinIds);
                }
            }

            this.formData.tdeliveryAddress = _data;
        }
    };

    //经费卡回调
    selectCard = result => {
        console.log(result);
        if (result) {
            this.formData.cardIds = result;
        }
    };

    //审批人回调
    selectMen = result => {
        console.log(result);
        if (result) {
            this.formData.piIds = result;
        }
    };

    //备注
    setRemarks = (suppId, remark) => {
        let remarkItem = {
            suppId,
            remark
        };

        let remarks = this.formData.remarks || [];
        let newRemarks = this.getNewRemarks(remarks, remarkItem);
        this.formData.remarks = newRemarks;
    };

    getNewRemarks = (remarks, remarkItem) => {
        let remarkCopy = JSON.parse(JSON.stringify(remarks));
        let remarkCopy2 = JSON.parse(JSON.stringify(remarks));
        if (remarkCopy.length == 0) {
            remarkCopy.push(remarkItem);
            return remarkCopy;
        } else {
            let index = -1;
            for (let i = 0; i < remarkCopy.length; i++) {
                let item = remarkCopy[i];
                if (item.suppId == remarkItem.suppId) {
                    index = i;
                    break;
                }
            }
            if (index == -1) {
                remarkCopy2.push(remarkItem);
            } else {
                remarkCopy2.splice(index, 1, remarkItem);
            }
            return remarkCopy2;
        }
    };

    //是否显示经费卡
    isShowCardByOrgId = () => {
        let orgIdList = ["2", "6", "8", "4", "3", "28"]; //不显示经费卡的医院ID
        if (orgIdList.indexOf(this.orgId) > -1) {
            this.setState({ isShowCard: false });
        }
    };

    // 中大供应商关系回调
    relationCb = (id, value) => {
        this.formData.relateInfo = value;
        this.setState({ ZDBetten: id });
    };

    getCarryFee = (id, ref) => {
        let url = `/store/api/order/getCarryFee`;
        let params = {
            addressID: id,
            isChangedAddress: 1,
            ids: this.formData.ids,
            refCouponIds: ref || []
        };
        REST.post(url, params).then(
            data => {
                this.formData.totalCarryFee = this.totalCarryFee(
                    data.shoppingCart,
                    "totalCarryFee"
                );
                this.setState({
                    cartInfo: data.shoppingCart
                });
            },
            error => {}
        );
    };

    clearCard = e => {
        this.formData.cardIds = [];
        this.setState({ yankeCard: null });
    };

    updateFrozen = (isfrozen) =>{
        this.setState({isFrozen:isfrozen})
    }

    addCard = type => {
        let _self = this;
        let passToModalData = {
            count: _self.totalAmount,
            selectDepart: this.formData.department.id
        };
        console.log("addCard");
        let modal = null;
        if (modal) {
            if (type == 1) {
                modal.show();
            } else {
                modal.hide();
            }
        }
        function closeModal(value) {
            if (
                value &&
                value.currentChildCard &&
                value.currentChildCard.banlanceAmount - passToModalData.count <
                    0
            ) {
                // modal.hide();
                ZenUI.ST("经费卡额度不足，请重新选择", 3);
            } else {
                if (Uts.isObject(value)) {
                    //enough
                    _self.setState({ yankeCard: [value.parentCard] });
                    // _self.selectCard([value.id]);
                    _self.formData.cardIds = [null];
                    _self.formData.subjectIdMapFreezeAmount = {
                        [value.currentChildCard.id]: _self.totalAmount
                    };
                    modal.hide();
                } else {
                    modal.hide();
                }
            }
        }
        function Content(props) {
            //chang the params when click ok
            props.item.passParams("abc");
            //change the footer button class
            React.useEffect(() => {
                props.item.changeFooterClass({
                    okClass: "testOk",
                    cancelClass: "testCancel"
                });
            });

            return <div>content</div>;
        }
        let options = {
            header:
                _self.state.yankeCard && _self.state.yankeCard.length
                    ? "修改经费卡"
                    : "选择经费卡",
            // footer: "test footer",
            content: YanKeSelectCard,
            size: "large",
            cbList: [closeModal],
            close: closeModal,
            // hideBackdrop: true,
            closeByBackDrop: true,
            extraData: passToModalData
        };
        modal = ZenModal.loadModal(options);
        // let modal = useModal(options);
        modal.show();
    };

    categoryDirectory(did) {
        let url = `/store/api/product/categoryDirectory/list`;
        // let data = {
        //     code: "0000",
        //     message: "success",
        //     total: 0,
        //     totalPage: 0,
        //     currentPage: 0,
        //     data: [
        //         {
        //             id: 247,
        //             code: "A110601",
        //             parentCode: "A1106",
        //             name: "酶类生化制剂"
        //         },
        //         {
        //             id: 248,
        //             code: "A11070903",
        //             parentCode: "A110709",
        //             name: "诊断用抗原"
        //         }
        //     ]
        // };

        REST.post(url, {}).then(
            data => {
                if(data) {
                    this.formData.applyProductReqs = [];
                    this.state.cartInfo.forEach((val, index) => {
                        val.cart.forEach((v, i) => {
                            if(!v.product.casNo) {
                                this.formData.applyProductReqs.push({
                                    productId: v.product && v.product.sn,
                                    directoryId:
                                        (v.product && v.product.categoryDirectoryId)||0
                                });
                            }
                        });
                    });
                    this.setState({ categoryList: data.data||[] });
                }
            },
            error => {
                // ToastUtils.hide();
            }
        );
      

    }

    editAddress1 = (id) =>{
        console.log(id);
        this.refs.OriginalInfo.editAddress2(id);
    }

    render() {
        const {
            cartInfo,
            deptId,
            minusPrice,
            supplierName,
            yankeCard,
            isShowCard,
            ZDBetten,
            serviceItem,
            commodityItem,
            hasLabel,
            isFrozen
        } = this.state;
        console.log("statementsRender",hasLabel);
        const clearCard = this.clearCard;
        return (
            <div>
                <StepHeader step={2} />
                {cartInfo && (
                    <ProductList
                        cartIds={this.cartIds}
                        cartInfo={cartInfo}
                        supplierName={supplierName}
                        isGroupbuying={this.groupbuyingId}
                        productCount={this.productCount}
                        setRemarks={this.setRemarks}
                        categoryList={this.state.categoryList}
                    />
                )}

                <OriginalInfo addressBc={this.addressBc.bind(this)} ref={"OriginalInfo"} updateStateLabel={this.updateStateLabel.bind(this)} />
                {["3"].indexOf(this.orgId) == -1 && (
                    <SubjectInfo changeDep={this.changeDep} selectMen={this.selectMen} updateFrozen={this.updateFrozen}/>
                )}
                {this.orgId != "36" &&this.orgId != "38" && isShowCard && deptId && (
                    <MoneyCard deptId={deptId} selectCard={this.selectCard} />
                )}
                {this.orgId == "36" && (
                    <div style={{ clear: "both" }} className="rj_subject_info">
                        <div className="rj_subject-wp">
                            {yankeCard &&
                                yankeCard.map(function(item, index) {
                                    return (
                                        <div
                                            key="item.id"
                                            className="zen_hover-wrap yanke-card zen_ps-re zen_bdr-8 zen_p-v-30 zen_p-h-24 zen_white yanke-m-bg-color zen_w-p25 zen_f-left"
                                        >
                                            <div className="zen_m-b-30 zen_fs-20">
                                                <span className="">
                                                    开启时间&nbsp;&nbsp;
                                                </span>
                                                <span>
                                                    {Filter.formatDate(
                                                        item.fundCards[0]
                                                            .startTime,
                                                        "Ym"
                                                    )}
                                                </span>
                                            </div>
                                            <div className="zen_m-b-15">
                                                <span className="zen_il-bl zen_w-90 zen_l-h-24">
                                                    项目名称：&nbsp;&nbsp;
                                                </span>
                                                <span>
                                                    {Filter.cutString(
                                                        item.projectName ||
                                                            item.subjectName,
                                                        25,
                                                        1
                                                    )}
                                                </span>
                                            </div>
                                            <div className="zen_m-b-15">
                                                <span className="zen_il-bl zen_w-90">
                                                    负责人：&nbsp;&nbsp;
                                                </span>
                                                <span>{item.managerName}</span>
                                            </div>

                                            <img
                                                src={xuanzhong}
                                                className="zen_ps-ab zen_b-0 zen_r-0"
                                                alt=""
                                            />
                                            <div
                                                onClick={clearCard}
                                                className="zen_bdr-8 zen_hover-show zen_ps-ab zen_t-0 zen_l-0 zen_b-0 zen_r-0 zen_bg-white yanke-card-hover"
                                            />
                                            <span
                                                className="zen_hover-show zen_ps-ab zen_t-12 zen_r-12 zen_fs-24 yanke-card-hover"
                                                onClick={clearCard}
                                            >
                                                X
                                            </span>
                                        </div>
                                    );
                                })}
                            <div
                                onClick={this.addCard}
                                className="rj_card_item-wp rj_card-border"
                            >
                                <div className="rj-l-add-wp">
                                    <img src={addPng} alt="" />
                                    <p>
                                        {yankeCard && yankeCard.length
                                            ? "修改经费卡"
                                            : "添加经费卡"}
                                    </p>
                                </div>
                            </div>
                            <div style={{ clear: "both" }} />
                        </div>
                    </div>
                )}
                {["3"].indexOf(this.orgId) > -1 && (
                    <Relationship cb={this.relationCb} />
                )}
                {this.totalMoneyInParent(cartInfo, minusPrice) && (
                    <ProcurementMoney
                        formData={this.formData}
                        moneyData={cartInfo}
                        minusPrice={minusPrice}
                        isGroupbuying={this.isGroupbuying}
                        isShowCard={isShowCard}
                        ZDBetten={ZDBetten}
                        serviceItem={serviceItem}
                        commodityItem={commodityItem}
                        labelEdit = {this.editAddress1}
                        hasLabel = {hasLabel}
                        isFrozen = {isFrozen}
                    />
                )}
            </div>
        );
    }
}

export default Statements;

// ReactDOM.render(<Statements />,document.getElementById('reactRoot'))
